package gruppoD;

import java.io.File;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

public class XML {

	private File fileXml;
	private Document doc;
	private DocumentBuilder dBuilder;

	public XML(File file) {
		if (file.exists()) {
			fileXml = file;
			parse();

		} else {
			// creo il file
			try {
				file.createNewFile();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	}

	private void parse() {
		try {
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory
					.newInstance();
			dBuilder = dbFactory.newDocumentBuilder();
			dBuilder.parse(fileXml);
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	private void writeToFile() throws TransformerException {
		// write the content into xml file
		TransformerFactory transformerFactory = TransformerFactory
				.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		//StreamResult result = new StreamResult(fileXml);
		//transformer.transform(source, result);
		System.out.println(source);
	}

	public void addParams(HashMap<String, String> parameters) {
		// operatore=MARIO-BIANCHI-5321&size=20&luogo=Centrale&modello=Sneaker-Plus(40)&data=010414
		Node registro = doc.getElementsByTagName("registro").item(0);
		Node azione = doc.createElement("azione").appendChild(
				doc.createTextNode("Carico"));

		Node operatore = doc.createElement("operatore").appendChild(
				doc.createTextNode(parameters.get("operatore")));
		Node stocks = doc.createElement("stocks").appendChild(doc.createTextNode(parameters.get("modello")));
		registro.appendChild(azione);
		registro.appendChild(operatore);
		registro.appendChild(stocks);
		try {
			writeToFile();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public void elencoCompleto() {

	}

	public void sintesi() {

	}
}
